//
//  KABMallBuyVC.m
//  kabu
//
//  Created by XiangDongMBP on 2017/2/25.
//  Copyright © 2017年 East. All rights reserved.
//

#import "KABMallBuyVC.h"
#import "GlobalHeader.h"
#import "UIColor+XDHex.h"
#import "KABThemeMallCRView.h"
#import "KABMallBuyCCell.h"
#import "UICollectionViewLeftAlignedLayout.h"
#import "KABModel.h"
#import "MBProgressHUD+XDPrompt.h"
#import <YYWebImage.h>

@interface KABMallBuyVC ()<UICollectionViewDelegate, UICollectionViewDataSource>

@property (weak, nonatomic) IBOutlet UIButton *emptyBtn;
@property (weak, nonatomic) IBOutlet UIImageView *productImgView;
@property (weak, nonatomic) IBOutlet UILabel *priceLabel;
@property (weak, nonatomic) IBOutlet UILabel *timeLabel;
@property (weak, nonatomic) IBOutlet UILabel *selPropertyLabel;
@property (weak, nonatomic) IBOutlet UIButton *closeBtn;
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property (weak, nonatomic) IBOutlet UIView *cntBgView;
@property (weak, nonatomic) IBOutlet UILabel *describeLabel;
@property (weak, nonatomic) IBOutlet UIButton *decreaseBtn;
@property (weak, nonatomic) IBOutlet UITextField *cntTextField;
@property (weak, nonatomic) IBOutlet UIButton *increaseBtn;
@property (weak, nonatomic) IBOutlet UIButton *sureBtn;
@property (strong, nonatomic) IBOutlet UILabel *testSizeLabel;  //!< 用来计算字符串宽度的


@end

static NSString * const reUseCellId = @"KABMallBuyCCell";
static NSString * const reUseHeadId = @"KABThemeMallCRView";

@implementation KABMallBuyVC

#pragma mark - life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initNavigationBar];
    [self initSubViews];
}

- (void)initNavigationBar {
    
}

- (void)initSubViews {
    [self.emptyBtn addTarget:self action:@selector(closeBtnTapped:) forControlEvents:UIControlEventTouchUpInside];
    [self.closeBtn addTarget:self action:@selector(closeBtnTapped:) forControlEvents:UIControlEventTouchUpInside];
    [self.decreaseBtn addTarget:self action:@selector(decreaseBtnTapped:) forControlEvents:UIControlEventTouchUpInside];
    [self.increaseBtn addTarget:self action:@selector(increaseBtnTapped:) forControlEvents:UIControlEventTouchUpInside];
    
    self.cntBgView.layer.borderWidth = 0.5;
    self.cntBgView.layer.borderColor = [UIColor xd_colorWithHex:KABGlobalColorBtnBorderColor].CGColor;
    self.cntTextField.layer.borderWidth = 0.5;
    self.cntTextField.layer.borderColor = [UIColor xd_colorWithHex:KABGlobalColorBtnBorderColor].CGColor;
    
    self.sureBtn.layer.masksToBounds = YES;
    self.sureBtn.layer.cornerRadius = CGRectGetHeight(self.sureBtn.bounds) / 2.0;
    [self.sureBtn addTarget:self action:@selector(sureBtnTapped:) forControlEvents:UIControlEventTouchUpInside];
    
    // 自定义布局
    UICollectionViewLeftAlignedLayout * layout = [[UICollectionViewLeftAlignedLayout alloc] init];
    layout.minimumLineSpacing = 10.0f;
    layout.minimumInteritemSpacing = 10.0f;
    layout.sectionInset = UIEdgeInsetsMake(0, 15, 10, 15);
    self.collectionView.collectionViewLayout = layout;
    
    UINib * cellNib = [UINib nibWithNibName:reUseCellId bundle:nil];
    [self.collectionView registerNib:cellNib forCellWithReuseIdentifier:reUseCellId];
    UINib * headNib = [UINib nibWithNibName:reUseHeadId bundle:nil];
    [self.collectionView registerNib:headNib forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:reUseHeadId];
//    self.collectionView.backgroundColor = [UIColor colorWithHexString:@"F1F5F8"];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    
    [self refreshWholeView];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - <UICollectionViewDataSource>
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return self.proDetail.product_property_list.count;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    KABProductProItem *item = self.proDetail.product_property_list[section];
    return item.model_list.count;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        KABThemeMallCRView *headView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:reUseHeadId forIndexPath:indexPath];
        [headView configViewWithItem:self.proDetail.product_property_list[indexPath.section]];
        return headView;
    }
    
    return nil;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    KABMallBuyCCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:reUseCellId forIndexPath:indexPath];
    KABProductProItem *item = self.proDetail.product_property_list[indexPath.section];
    KABProModelListItem *modelItem = item.model_list[indexPath.item];
    [cell configViewWithModelItem:modelItem isSel:(item.model_id == modelItem.model_id)];
//    [cell configViewWithModelItem:modelItem isSel:NO];
    return cell;
}

#pragma mark - <UICollectionViewDelegateFlowLayout>代理
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    return CGSizeMake(CGRectGetWidth(self.view.bounds), 30.f);
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    KABProductProItem *item = self.proDetail.product_property_list[indexPath.section];
    KABProModelListItem *modelItem = item.model_list[indexPath.item];
    self.testSizeLabel.text = modelItem.content;
    CGSize size = [self.testSizeLabel sizeThatFits:CGSizeMake(CGFLOAT_MAX, 25.0f)];
    return CGSizeMake(size.width + 10 * 2, 26.0f);
}

#pragma mark - <UICollectionViewDelegate>
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    KABProductProItem *item = self.proDetail.product_property_list[indexPath.section];
    KABProModelListItem *modelItem = item.model_list[indexPath.item];
    item.model_id = modelItem.model_id;
    [self.proDetail modelIdMergeToSkuId];
//    [collectionView reloadSections:[NSIndexSet indexSetWithIndex:indexPath.section]];
    [self refreshWholeView];
}

#pragma mark - event response
- (void)closeBtnTapped:(UIButton *)btn {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)decreaseBtnTapped:(UIButton *)btn {
    if (self.proDetail.number > 1) {
        --self.proDetail.number;
        [self refreshWholeView];
    } else {
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"不能更少了喔"];
    }
}

- (void)increaseBtnTapped:(UIButton *)btn {
    if (self.proDetail.number < self.proDetail.selStock) {
        ++self.proDetail.number;
        [self refreshWholeView];
    } else {
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"库存不足"];
    }
}

- (void)sureBtnTapped:(UIButton *)btn {
    if (!self.proDetail.hasSelModel) {
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"请先选择商品属性"];
        return;
    }
    
    [self dismissViewControllerAnimated:YES completion:^{
        if (self.completeBlock) {
            self.completeBlock();
            self.completeBlock = nil;
        }
    }];
}

#pragma mark - private methods
- (void)refreshWholeView {
    [self.productImgView yy_setImageWithURL:[NSURL URLWithString:self.proDetail.product_cover_image_url] placeholder:[KABDefaultVarModel sharedInstance].bigDefaultImg options:YYWebImageOptionSetImageWithFadeAnimation completion:nil];
    
    self.priceLabel.text = [NSString stringWithFormat:@"￥%.2f", self.proDetail.selOriginalPrice / 100.0];
    self.timeLabel.text = [NSString stringWithFormat:@"库存%zd", self.proDetail.selStock];
    self.selPropertyLabel.text = [NSString stringWithFormat:@"已选：%@", self.proDetail.selPropertyStr];
    self.cntTextField.text = [NSString stringWithFormat:@"%zd", self.proDetail.number];
    
    [self.collectionView reloadData];
}

#pragma mark - network request
#pragma mark - getters and setters

@end
